/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets;

import com.codemagi.servlets.model.*;
import com.codemagi.util.*;
import java.io.Serializable;
import java.util.*;
import org.apache.commons.collections.map.*;
import org.apache.log4j.Logger;

/**
 * This class can be used to cache rendered Node content.
 *
 *  @version 1.0
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public class NodeCache implements Serializable {

    Logger log = Logger.getLogger(this.getClass());

    /** Singleton instance */
    private final static NodeCache instance = new NodeCache();

    /** The cache */
    MultiKeyMap cache = MultiKeyMap.decorate(new LRUMap(100));

    
    /**                                                                                                               
     * Private class constructor. This class was not meant to be instantiated!               
     */
    private NodeCache() {
        //nada                                                    
    }

    /**                                                                                                                            
     * Returns a singleton instance of the NodeCache
     */
    public static final NodeCache getInstance() {
        return instance;
    }


    /**
     * Adds a Node to the cache
     * 
     * @param Node        The Node to store 
     * @param description Description of the content to store, for example a link URL
     * @param value       The rendered content to store
     */
    public void store(Node node, String description, String value) {

	log.debug("STORING: " + node + ", " + description); // + ", " + value);

	//sanity check: Don't waste space if we aren't really storing anything
	if (node == null || Utils.isEmpty(description) || Utils.isEmpty(value)) return;

	//insert into the cache
	cache.put(node.getId(), description, new NodeEntry(node.getModifiedDate(), value));
    }


    /** 
     * Gets a Node from the cache. This method checks whether the passed-in Node and description
     * has an entry in the cache, and whether that entry is older than the last-modified date of
     * of the Node. 
     * 
     * If the data in the cache is older than the node itself, or if there is no data in the cache, 
     * null is returned.
     * 
     * @param node        The node to get
     * @param description Description of the content to get
     */
    public String retrieve(Node node, String description) {
	
	//sanity check 
	if (node == null || Utils.isEmpty(description)) return null;

	log.debug("RETRIEVING: " + node + ", " + description);

	//try to retrieve the entry from cache
	NodeEntry entry = (NodeEntry)cache.get(node.getId(), description);
	log.debug("ENTRY: " + entry);
	if (entry == null) return null;

	//check the node dates against the oject in cache
	log.debug("CHECKING node: " + node.getModifiedDate() + " AGAINST cacheNode: " + entry.getNodeDate());
	if ( DateUtils.isGreater(node.getModifiedDate(), entry.getNodeDate()) ) return null;

	//checks passed, return the cached value     
	return entry.getValue(); 
    }


    /**
     * Clears the NodeCache for a particular node ID
     */
    public void clear(Integer nodeId) {
	cache.removeAll(nodeId);
    }


    class NodeEntry {

	private Date nodeDate;
	private String value;

	public NodeEntry(Date nodeDate, String value) {
	    this.nodeDate = nodeDate;
	    this.value    = value;
	}

	public void setNodeDate(Date newValue) {
	    nodeDate = newValue;
	}

	public Date getNodeDate() {
	    return nodeDate;
	}

	public void setValue(String newValue) {
	    value = newValue;
	} 

	public String getValue() {
	    return value;
	}
    }

}
